<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <!--引入的vue.js-->
    <script src="../../js/vue.js"></script>
    <!--引入elementUI的css-->
    <link type="text/css" rel="stylesheet" href="../../css/index.css">
    <!--引入elementUI的js-->
    <script src="../../js/index.js"></script>
    <!--引入axios.js-->
    <script src="../../js/axios.min.js"></script>
</head>
<style>
    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
        font-size: 30px;
    }
    .image-slot i {
        font-size: 20px;
    }
</style>

<body>
<!-- Vue应用根元素 -->
<div id="app" class="app1">
    <!-- 搜索区域 - 使用Element UI栅格系统布局 -->
    <el-row>
        <!-- 用户ID搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.userId"
                      placeholder="请输入用户ID"
                      size="small">
            </el-input>
        </el-col>

        <!-- 用户名搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.userName"
                      placeholder="请输入用户名"
                      size="small">
            </el-input>
        </el-col>

        <!-- 真实姓名搜索框 -->
        <el-col :span="6">
            <el-input size="mini"
                      v-model="searchForm.nickName"
                      placeholder="请输入用户真实姓名"
                      size="small">
            </el-input>
        </el-col>

        <!-- 搜索和添加按钮 -->
        <el-col :span="6">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-search"
                       @click="search"
                       size="small">
                搜索
            </el-button>
            &nbsp;&nbsp;
            <el-button size="mini"
                       type="primary"
                       @click="handleAdd">
                添加
            </el-button>
        </el-col>
    </el-row>

    <!-- 用户数据表格 -->
    <el-table :data="tableData" style="width: 100%">
        <!-- 用户ID列 -->
        <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>

        <!-- 部门名称列 -->
        <el-table-column prop="dept.deptName" label="部门名称" width="120"></el-table-column>

        <!-- 用户姓名或昵称列 -->
        <el-table-column prop="nickName" label="用户姓名" width="120"></el-table-column>

        <!-- 用户名(唯一)列 -->
        <el-table-column prop="userName" label="用户名" width="120"></el-table-column>

        <!-- 用户邮箱列 -->
        <el-table-column prop="email" label="邮箱" width="150"></el-table-column>

        <!-- 手机号码列 -->
        <el-table-column prop="phonenumber" label="手机号" width="120"></el-table-column>

        <!-- 用户性别列 -->
        <el-table-column prop="sex" label="性别" width="80">
            <template slot-scope="scope">
                <span v-if="scope.row.sex === '0'">男</span>
                <span v-else-if="scope.row.sex === '1'">女</span>
                <span v-else>未知</span>
            </template>
        </el-table-column>

        <!-- 帐号状态列 -->
        <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
            </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
                {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ').substring(0, 19) : '' }}
            </template>
        </el-table-column>

        <!-- 在创建时间列后添加头像列 -->
        <el-table-column label="用户头像" width="120">
            <template slot-scope="scope">
                <div v-if="scope.row.avatar">
                    <el-image
                            :src="scope.row.avatar"
                            :preview-src-list="[scope.row.avatar]"
                            style="width: 80px; height: 80px;"
                            fit="cover"
                            lazy>
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </div>
                <div v-else>
                    <span>无</span>
                </div>
            </template>
        </el-table-column>


        <!-- 操作列 -->
        <el-table-column label="操作" fixed="right" width="200">
            <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>

                <!-- 授权按钮 -->
                <el-button size="mini" type="warning" @click="handleAuth(scope.$index, scope.row)">
                    授权
                </el-button>

                <!-- 删除按钮 -->
                <!--<el-button size="mini"
                           type="danger"
                           @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>-->
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                        :disabled="scope.row.userId === 1"
                :title="scope.row.userId === 1 ? '该用户禁止删除' : ''">  <!-- 核心条件：ID=1时禁用 --><!-- hover提示 -->
                删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,5,10,15,20,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 添加/更新用户对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px">
        <!-- 表单 -->
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <!-- 部门选择 -->
            <el-form-item label="所属部门" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 100%">
                    <el-option
                            v-for="item in deptList"
                            :key="item.deptId"
                            :label="item.deptName"
                            :value="item.deptId">
                    </el-option>
                </el-select>
            </el-form-item>

            <!-- 用户姓名输入框 -->
            <el-form-item label="用户姓名" prop="nickName">
                <el-input v-model="form.nickName" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 用户名输入框 -->
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="form.userName" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 邮箱输入框 -->
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 手机号输入框 -->
            <el-form-item label="手机号" prop="phonenumber">
                <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
            </el-form-item>

            <!-- 性别选择框 -->
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                    <el-radio label="2">未知</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 密码输入框 -->
            <el-form-item label="密码" prop="password" v-if="title === '添加用户'">
                <el-input v-model="form.password" autocomplete="off" show-password></el-input>
            </el-form-item>

            <!-- 状态选择框 -->
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                    <el-radio label="0">正常</el-radio>
                    <el-radio label="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 在表单中添加头像上传字段 -->
            <el-form-item label="用户头像" prop="avatar">
                <el-upload
                        class="upload-demo"
                        action="/vegetablemarketexpress/user/uploadAvatarImage"
                        name="pic"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :before-upload="beforeAvatarUpload"
                        :limit="1"
                        :file-list="avatarFileList"
                        list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                </el-upload>
                <el-input v-model="form.avatar" type="hidden"></el-input>
                <div v-if="form.avatar">
                    <img :src="form.avatar" style="width: 100px; height: 100px; margin-top: 10px;" />
                </div>
            </el-form-item>


            <!-- 备注输入框 -->
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" autocomplete="off" :rows="3"></el-input>
            </el-form-item>
        </el-form>

        <!-- 对话框底部按钮 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 用户授权对话框 -->
    <el-dialog title="用户授权" :visible.sync="authDialogVisible" width="500px">
        <el-form :model="authForm" ref="authForm" label-width="80px">
            <el-form-item label="用户姓名">
                <el-input v-model="authForm.nickName" readonly></el-input>
            </el-form-item>
            <el-form-item label="角色授权">
                <el-select v-model="authForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                    <el-option
                            v-for="item in roleList"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="authDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAuthForm('authForm')">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [],              // 表格数据
                currentPage: 1,             // 当前页码
                pageSize: 5,                // 每页显示条数
                total: 0,                   // 总条数
                deptList: [],               // 部门列表
                roleList: [],               // 角色列表
                searchForm: {               // 搜索条件
                    userId: '',
                    userName: '',
                    nickName: ''  // 对应User实体类的nickName属性
                },
                title: '添加用户',           // 对话框标题
                dialogFormVisible: false,   // 用户表单对话框是否可见
                authDialogVisible: false,   // 授权对话框是否可见
                form: {                     // 用户表单数据
                    userId: '',
                    deptId: '',
                    nickName: '',
                    userName: '',
                    email: '',
                    phonenumber: '',
                    sex: '0',
                    password: '',
                    status: '0',
                    remark: ''
                },
                authForm: {                 // 授权表单数据
                    userId: '',
                    nickName: '',
                    roleIds: []  // 多选角色ID
                },
                avatarFileList: []  ,       // 头像上传文件列表

                // 表单验证规则
                rules: {
                    deptId: [
                        { required: true, message: '请选择所属部门', trigger: 'change' }
                    ],
                    nickName: [
                        { required: true, message: '请输入用户姓名', trigger: 'blur' }
                    ],
                    userName: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
                    ],
                    phonenumber: [
                        { required: true, message: '请输入手机号', trigger: 'blur' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
                    ],
                    status: [
                        { required: true, message: '请选择状态', trigger: 'change' }
                    ]
                }
            }
        },
        created() {
            // 页面加载时加载数据
            this.loadData();
            this.loadDeptList();
            this.loadRoleList();
        },
        methods: {
            // 加载用户数据
            loadData() {
                let _this = this;
                // 发送POST请求获取分页数据
                axios.post('/vegetablemarketexpress/user/selectUserList', {
                    "pageNo": this.currentPage,
                    "pageSize": this.pageSize,
                    "data": this.searchForm
                }).then(function(response) {
                    if (response.data.code == 200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    }
                }).catch(function(error) {
                    console.log(error);
                    _this.$message.error('数据加载失败');
                });
            },

            // 加载部门列表
            loadDeptList() {
                let _this = this;
                axios.get('/vegetablemarketexpress/dept/listAllNormal')
                    .then(function(response) {
                        if (response.data.code == 200) {
                            _this.deptList = response.data.data;
                        }
                    }).catch(function(error) {
                    console.log(error);
                    _this.$message.error('部门数据加载失败');
                });
            },

            // 加载角色列表
            loadRoleList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/role/queryByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": {}
                }).then(function(response) {
                    if (response.data.code == 200) {
                        _this.roleList = response.data.data.list;
                    }
                }).catch(function(error) {
                    console.log(error);
                    _this.$message.error('角色数据加载失败');
                });
            },

            // 每页条数改变时触发
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadData();
            },

            // 当前页改变时触发
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },

            // 搜索功能
            search() {
                this.currentPage = 1;
                this.loadData();
            },

            // 提交表单
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let uri = '/vegetablemarketexpress/user/insertUser';
                        if (this.title == '用户更新') {
                            uri = '/vegetablemarketexpress/user/updateUser';
                        }

                        let _this = this;
                        let submitForm = JSON.parse(JSON.stringify(this.form));

                        // 处理部门对象
                        if (submitForm.dept) {
                            submitForm.deptId = submitForm.dept.deptId;
                            delete submitForm.dept;
                        }

                        axios.post(uri, submitForm)
                            .then(function(response) {
                                if (response.data.code == 200) {
                                    _this.$message({
                                        message: '操作成功',
                                        type: 'success'
                                    });
                                    _this.loadData();
                                    _this.dialogFormVisible = false;
                                } else {
                                    _this.$message.error('操作失败 ' );
                                }
                            })
                            .catch(function(error) {
                                console.log(error);
                                _this.$message.error('操作异常');
                            });
                    } else {
                        this.$message.error('表单验证失败');
                    }
                });
            },

            // 提交授权表单
            submitAuthForm(formName) {
                let _this = this;
                let submitForm = {
                    userId: this.authForm.userId,
                    roleIds: this.authForm.roleIds
                };

                axios.post('/vegetablemarketexpress/user/authRole', submitForm)
                    .then(function(response) {
                        if (response.data.code == 200) {
                            _this.$message({
                                message: '授权成功',
                                type: 'success'
                            });
                            _this.loadData();
                            _this.authDialogVisible = false;
                        } else {
                            _this.$message.error('授权失败: ' + response.data.msg);
                        }
                    })
                    .catch(function(error) {
                        console.log(error);
                        _this.$message.error('授权异常');
                    });
            },

            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            // 处理添加用户
            handleAdd() {
                this.dialogFormVisible = true;
                this.title = "添加用户";
                this.form = {
                    userId: '',
                    deptId: '',
                    nickName: '',
                    userName: '',
                    email: '',
                    phonenumber: '',
                    sex: '0',
                    password: '',
                    status: '0',
                    remark: '',
                    avatar: ''  // 初始化头像字段
                };
                this.avatarFileList = [];  // 清空文件列表
            },

            // 处理编辑用户
            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.title = "用户更新";
                // 深拷贝避免直接引用
                this.form = JSON.parse(JSON.stringify(row));
                // 初始化头像文件列表用于预览
                this.avatarFileList = [];
                if (this.form.avatar) {
                    const fileName = this.form.avatar.substring(this.form.avatar.lastIndexOf('/') + 1);
                    this.avatarFileList.push({
                        name: fileName,
                        url: this.form.avatar
                    });
                }
            },

            // 头像上传成功处理
            handleAvatarSuccess(response, file, fileList) {
                if (response.code === 200) {
                    // 后端返回 {filePath: "图片地址", originName: "原文件名"}
                    this.form.avatar = response.data.filePath;
                    this.$message.success('头像上传成功');
                } else {
                    this.$message.error('头像上传失败: ' + (response.msg || '未知错误'));
                }
            },

            // 头像上传失败处理
            handleAvatarError(err, file, fileList) {
                this.$message.error('头像上传失败');
            },

            // 头像上传前检查
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('头像只能上传 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('头像大小不能超过 2MB!');
                    return false;
                }
                return true;
            },

            // 处理用户授权
            handleAuth(index, row) {
                let _this = this;
                // 获取用户详细信息（包含角色信息）
                axios.get('/vegetablemarketexpress/user/getUserWithRoles/' + row.userId)
                    .then(function(response) {
                        if (response.data.code == 200) {
                            let user = response.data.data;
                            _this.authDialogVisible = true;
                            _this.authForm.userId = user.userId;
                            _this.authForm.nickName = user.nickName;
                            // 设置选中的角色ID
                            _this.authForm.roleIds = user.roleIds || [];
                        } else {
                            _this.$message.error('获取用户信息失败: ' + response.data.msg);
                        }
                    })
                    .catch(function(error) {
                        console.log(error);
                        _this.$message.error('获取用户信息异常');
                    });
            },

            // 处理删除用户
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    // 发送删除请求
                    axios.delete('/vegetablemarketexpress/user/deleteUserById?userId=' + row.userId)
                        .then(function(response) {
                            if (response.data.code == 200) {
                                _this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                _this.loadData();
                            } else {
                                _this.$message.error('删除失败: ' + response.data.msg);
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('删除异常');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    });
</script>
</body>
</html>
